/*
 *
 * @ProjectName:    my_umi_app
 * @Package:
 * @ClassName:      add_category
 * @Description:    添加分类
 * @Author:         SuPeiSen
 * @CreateDate:     2021/1/20 4:58 下午
 * @UpdateDate:     2021/1/20 4:58 下午
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */

import React, { useRef, useState } from 'react';
import { Button, Form, Input, Row, Switch, message } from 'antd';
import { addCategoryByAdminApi } from '@/service/category_api';
import { history } from 'umi';

export default () => {
  const [loading, setLoading] = useState<boolean>(false);
  const categoryNameRef = useRef<Input>(null);
  const categoryRouteRef = useRef<Input>(null);
  const categoryPxRef = useRef<Input>(null);

  let selectStatus = true;

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
  };

  const submitInput = async () => {
    setLoading(true);
    const param = {
      category_name: categoryNameRef.current!.state.value,
      category_route: categoryRouteRef.current!.state.value,
      px: Number(categoryPxRef.current?.state.value ?? 99),
      status: selectStatus ? 1 : -1,
    };
    const model = await addCategoryByAdminApi(param, () => setLoading(false));
    if (model.success) {
      message.success('添加成功');
      history.push('/admin/category/category_list');
    } else {
      message.error('添加失败');
    }
  };

  const switchOnChange = (value: boolean) => {
    selectStatus = value;
  };

  return (
    <div className="main_div">
      <Row justify="start">
        <Form {...layout} onFinish={submitInput}>
          <Form.Item
            label="分类名称"
            name="category_name"
            rules={[
              {
                required: true,
                message: '分类名称必须',
              },
            ]}
          >
            <Input className="inputLen" ref={categoryNameRef} />
          </Form.Item>

          <Form.Item
            label="分类路由"
            name="category_path"
            rules={[
              {
                required: true,
                message: '分类路由地址必须',
              },
            ]}
          >
            <Input className="inputLen" ref={categoryRouteRef} />
          </Form.Item>

          <Form.Item label="排序" name="category_px">
            <Input className="inputLen" ref={categoryPxRef} />
          </Form.Item>

          <Form.Item label="状态" valuePropName="category_status">
            <Switch defaultChecked onChange={switchOnChange} />
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              loading={loading}
            >
              保存
            </Button>
          </Form.Item>
        </Form>
      </Row>
    </div>
  );
};
